<template>
  <view class="update-password-container">
    <view class="form-group">
      <view class="input-group">
        <text class="label">邮箱</text>
        <input 
          type="text" 
          v-model="form.email" 
          placeholder="请输入邮箱" 
          class="input"
          disabled
        />
      </view>
      
      <view class="input-group">
        <text class="label">验证码</text>
        <view class="code-input-group">
          <input 
            type="text" 
            v-model="form.code" 
            placeholder="请输入验证码" 
            class="input code-input"
          />
          <button 
            class="send-code-btn" 
            :disabled="isCountingDown" 
            @click="handleSendCode"
          >
            {{ countDownText }}
          </button>
        </view>
      </view>
      
      <view class="input-group">
        <text class="label">新密码</text>
        <input 
          type="password" 
          v-model="form.newPassword" 
          placeholder="请输入新密码" 
          class="input"
        />
      </view>
      
      <view class="input-group">
        <text class="label">确认密码</text>
        <input 
          type="password" 
          v-model="form.confirmPassword" 
          placeholder="请再次输入新密码" 
          class="input"
        />
      </view>
    </view>
    
    <button class="submit-btn" @click="handleSubmit">确认修改</button>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { request } from '@/utiles/request'

const form = ref({
  email: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

const countdown = ref(0)
const isCountingDown = computed(() => countdown.value > 0)
const countDownText = computed(() => isCountingDown.value ? `${countdown.value}s后重新发送` : '发送验证码')

// 页面加载时自动填充邮箱
onMounted(() => {
  const local = uni.getStorageSync('userInfo');
  if (local) {
    try {
      const obj = typeof local === 'string' ? JSON.parse(local) : local;
      form.value.email = (obj.data || obj).email || '';
    } catch (e) {
      form.value.email = '';
    }
  }
});

// 发送验证码
async function handleSendCode() {
  if (!form.value.email) {
    uni.showToast({
      title: '邮箱为空',
      icon: 'none'
    })
    return
  }
  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(form.value.email)) {
    uni.showToast({
      title: '邮箱格式不正确',
      icon: 'none'
    })
    return
  }
  try {
    const res = await request({
      url: '/admin/api/user/send-verification-code',
      method: 'POST',
      data: {
        email: form.value.email
      }
    })
    if (res.data.code === 200) {
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      })
      startCountdown()
    } else {
      uni.showToast({
        title: res.data.message || '发送失败',
        icon: 'none'
      })
    }
  } catch (e) {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

// 倒计时
function startCountdown() {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 提交修改
async function handleSubmit() {
  // 表单验证
  if (!form.value.email || !form.value.code || !form.value.newPassword || !form.value.confirmPassword) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }
  if (form.value.newPassword !== form.value.confirmPassword) {
    uni.showToast({
      title: '两次输入的密码不一致',
      icon: 'none'
    })
    return
  }
  // 密码强度验证：至少8位且包含字母和数字
  const pwd = form.value.newPassword
  if (pwd.length < 8 || !/[A-Za-z]/.test(pwd) || !/\d/.test(pwd)) {
    uni.showToast({
      title: '密码需至少8位且包含字母和数字',
      icon: 'none'
    })
    return
  }
  // 获取user_id
  let user_id = ''
  const local = uni.getStorageSync('userInfo');
  if (local) {
    try {
      const obj = typeof local === 'string' ? JSON.parse(local) : local;
      user_id = (obj.data || obj).user_id || (obj.data || obj).id || '';
    } catch (e) {
      user_id = '';
    }
  }
  if (!user_id) {
    uni.showToast({
      title: '用户信息异常，请重新登录',
      icon: 'none'
    })
    return
  }
  try {
    const res = await request({
      url: '/admin/api/user/reset-password',
      method: 'POST',
      data: {
        user_id,
        email: form.value.email,
        verification_code: form.value.code,
        new_password: form.value.newPassword
      }
    })
    if (res.data.code === 200) {
      uni.showToast({
        title: '密码重置成功',
        icon: 'success'
      })
      // 清除本地缓存并跳转到登录页
      setTimeout(() => {
        uni.clearStorageSync();
        uni.reLaunch({ url: '/pages/login/login' });
      }, 1500)
    } else {
      uni.showToast({
        title: res.data.message || '重置失败',
        icon: 'none'
      })
    }
  } catch (e) {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}
</script>

<style>
.update-password-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 30rpx;
}

.form-group {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
}

.input-group {
  margin-bottom: 30rpx;
}

.input-group:last-child {
  margin-bottom: 0;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
}

.input {
  width: 100%;
  height: 80rpx;
  background: #f5f7fa;
  border-radius: 8rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
}

.code-input-group {
  display: flex;
  gap: 20rpx;
}

.code-input {
  flex: 1;
}

.send-code-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: #1890ff;
  color: #fff;
  font-size: 26rpx;
  border-radius: 8rpx;
  padding: 0;
}

.send-code-btn[disabled] {
  background: #ccc;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background: #1890ff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  margin-top: 60rpx;
}
</style>